<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <title>广场</title>
    <link rel="stylesheet" type="text/css" href="../..//css/api.css" />
    <link rel="stylesheet" type="text/css" href="../../css/style.css" />
    <link rel="stylesheet" href="../../css/aui.css">
    <link rel="stylesheet" href="../../icon/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="../../icon/iconfont.css">
    <link rel="stylesheet" href="../../css/frame2/compile.css">
    <style>
        .removeimg {
            color: red;
            position: absolute;
            font-size: 20px;
            right: -10px;
            top: -10px;
        }

        .aui-progress-bar {
            background: #E4C493;
        }

        #progress {
            position: absolute;
            color: #E4C493;
            font-size: 13px;
            left: 36%;
            top: -.2rem;
        }

        .progressbox {
            display: none;
            position: relative;
        }
    </style>
</head>

<body style="background-color:#fff">
    <div class="compile">
        <div class="header">
            <div class="header_left">
                <span class="iconfont icon-fanhui" onClick="api.closeWin()"></span>
                <span>发表</span>
            </div>
            <div class="header_right">
                <!-- <button onClick="api.closeWin()">提交</button> -->
                <button id="postAction">提交</button>
            </div>
            <textarea id="desc" name="name" rows="5" cols="80" placeholder="这一刻的想法......" autofocus="autofocus"></textarea>
            <div id="imglistBox"></div>
        </div>
        <img id="UploadImgs" src="../../image/tianjia.png" alt="">
    </div>
    <div class="progressbox">
        <div class="aui-progress aui-progress-xs" style="width: 30%;margin: .2rem .8rem;">
            <div class="aui-progress-bar" style="width:0%;"></div>
        </div>
        <span id="progress">20%</span>
    </div>
</body>
<script type="text/javascript" src="../../script/api.js"></script>
<script type="text/javascript" src="../../script/dns.js"></script>
<script type="text/javascript" src="../../lib/artTemplate/template.js"></script>
<script type="text/javascript" src="../../script/jquery-3.3.1.js"></script>
<script type="text/javascript" src="../../script/aui-toast.js"></script>
<script id="uploadimgList" type="text/html">
    {{each data as value index}}
    <div style="width:3rem; height:3rem;  position: relative;float:left; margin:0 1rem .5rem 0;" data-id="{{data[index].id}}">
        <img style="width:3rem; height:3rem;" src="{{data[index].src}}" alt="" />
        <i class="fa fa-minus-circle removeimg" style="cursor: pointer;" data-delid="{{data[index].id}}"></i>
    </div>
    {{/each}}
</script>
<script>
    var toast = new auiToast({
    })
    var imgsListarr = new Array();
    var imgs = new Array();
    $(document).ready(function() {
        //console.log(localStorage.getItem('token'));
        //发布的上传图片
        $('#UploadImgs').click(function() {
            var len = imgsListarr.length;
            if (len >= 9) {
                toast.fail({
                    title:"图片数量达到上限!",
                    duration:1500
                });
                return;
            } else {
                uploadImgs('storage');
            }

        });
        //删除当前的图片
        $(document).on('click', '.removeimg', function() {
            var delid = $(this).data('delid');
            for (var i = imgsListarr.length - 1; i >= 0; i--) {
                if (imgsListarr[i].id == delid) {
                    imgsListarr.splice(i, 1)
                };
            }
            $(this).parent().remove();
        });
    });

    function uploadImgs(perm) {
      if (!confirmPer(perm)) {
          toast.fail({
              title:"您当前没权限!",
              duration:1500
          });
          return;
      }
        if (perm == 'storage') { //相册权限
        var UIMediaScanner = api.require('UIMediaScanner');
        UIMediaScanner.open({
            type: 'picture',
            column: 5,
            classify: true,
            max: 9,
            sort: {
                key: 'time',
                order: 'desc'
            },
            texts: {
                stateText: '已选择*项',
                cancelText: '取消',
                finishText: '完成'
            },
            styles: {
                bg: '#fff',
                mark: {
                    icon: '',
                    position: 'bottom_left',
                    size: 20
                },
                nav: {
                    bg: '#eee',
                    stateColor: '#000',
                    stateSize: 18,
                    cancelBg: 'rgba(0,0,0,0)',
                    cancelColor: '#000',
                    cancelSize: 18,
                    finishBg: 'rgba(0,0,0,0)',
                    finishColor: '#000',
                    finishSize: 18
                }
            },
            scrollToBottom: {
                intervalTime: 3,
                anim: true
            },
            exchange: true,
            rotation: true
        }, function(ret) {
            if (ret) {
                var list = ret.list;
                var systemType = api.systemType;
                if (ret.eventType != 'cancel') {
                    if (systemType == 'ios') { //如果是 ios 本地路径需要 转化下才能拿到文件本地资源
                        for (i in list) {
                            var baseUrl = 'http://cloud.jinshouzhou.com/'; //七牛给你的测试域名，也可使用自己捆绑的域名youe.xxx.com
                            var obj = api.require('qiniuUpfile');
                            var UIMediaScanner = api.require('UIMediaScanner');
                            UIMediaScanner.transPath({
                                path: list[i]['path']  //在 iOS 平台上需要先调用 transPath 接口将路径转换之后才能读取目标资源媒体文件。
                            }, function(ret, err) {
                                if (ret) {
                                    var pathnew = ret.path; //ios路径转换 （读取目标资源媒体文件）
                                    var filename = 'uploads/user/20190604/' + (new Date()).getTime() + Math.floor(Math.random() * 100 + 1);
                                    obj.upfile({
                                        file: pathnew,
                                        name: filename
                                    }, function(ret, err) {
                                        console.log(JSON.stringify(ret));
                                        if (ret.status) {
                                            if (ret.oper == "complete") {
                                                $('.progressbox').hide();
                                                $('.aui-progress-bar').css('width', '0px');
                                                //图片提交给后台
                                                $.ajax({
                                                    url: dns + 'upload/image/qiniu',
                                                    type: 'POST',
                                                    async: false,
                                                    data: {
                                                        'filename': ret.info.key
                                                    },
                                                    beforeSend: function(request) {
                                                        request.setRequestHeader("token", localStorage.getItem('token'));
                                                    },
                                                    success: function(res) {
                                                        console.log(JSON.stringify(res));
                                                        imgsListarr.push({
                                                            'id': res.data.id,
                                                            'src': res.data.src + '?imageslim'
                                                        })
                                                        var html = template('uploadimgList', {
                                                            data: imgsListarr
                                                        });
                                                        $('#imglistBox').html(html);
                                                    },
                                                    error: function(err) {
                                                        toast.fail({
                                                            title:JSON.parse(err.responseText).msg,
                                                            duration:1500
                                                        });
                                                        return;
                                                    }
                                                });

                                            } else if (ret.oper == "progress") {
                                                $('.progressbox').show();
                                                //上传过程中获取进度数据
                                                $('#progress').html(Math.floor(ret.percent) + '%');
                                                $('.aui-progress-bar').css('width', Math.floor(ret.percent) + '%');
                                                //$api.text(a, ret.percent);
                                            }
                                        }
                                    });

                                } else {
                                    alert(JSON.stringify(err));
                                }
                            });
                        }
                    };
                    if (systemType == 'android') {
                        for (i in list) {
                            // var filename ='uploads/user/20190604/' + (new Date()).getTime() + Math.floor(Math.random()*100+1);
                            var baseUrl = 'http://cloud.jinshouzhou.com/'; //七牛给你的测试域名，也可使用自己捆绑的域名youe.xxx.com
                            var obj = api.require('qiniuUpfile');
                            var filename = 'uploads/user/20190604/' + (new Date()).getTime() + Math.floor(Math.random() * 100 + 1);
                            obj.upfile({
                                file: list[i]['path'],
                                name: filename
                            }, function(ret, err) {
                                console.log(JSON.stringify(ret));
                                if (ret.status) {
                                    if (ret.oper == "complete") {
                                        $('.progressbox').hide();
                                        $('.aui-progress-bar').css('width', '0px');
                                        //图片提交给后台
                                        $.ajax({
                                            url: dns + 'upload/image/qiniu',
                                            type: 'POST',
                                            async: false,
                                            data: {
                                                'filename': ret.info.key
                                            },
                                            beforeSend: function(request) {
                                                request.setRequestHeader("token", localStorage.getItem('token'));
                                            },
                                            success: function(res) {
                                                console.log(JSON.stringify(res));
                                                imgsListarr.push({
                                                    'id': res.data.id,
                                                    'src': res.data.src + '?imageslim'
                                                })
                                                var html = template('uploadimgList', {
                                                    data: imgsListarr
                                                });
                                                $('#imglistBox').html(html);
                                            },
                                            error: function(err) {
                                                toast.fail({
                                                    title:JSON.parse(err.responseText).msg,
                                                    duration:1500
                                                });
                                                return;
                                            }
                                        });

                                    } else if (ret.oper == "progress") {
                                        $('.progressbox').show();
                                        //上传过程中获取进度数据
                                        $('#progress').html(Math.floor(ret.percent) + '%');
                                        $('.aui-progress-bar').css('width', Math.floor(ret.percent) + '%');
                                        //$api.text(a, ret.percent);
                                    }
                                }
                            });
                        }
                    }
                }
                return;
                api.sendEvent({
                    name: 'sendImg',
                    extra: {
                        imgArr: arr,
                        text: vm.text
                    }
                });
            }
        });
      }
    }

    $('#postAction').click(function() {
        var desc = $('#desc').val();
        var imagelen = $('#imglistBox div').length;
        var imgId = [];
        $('#imglistBox div').each(function() {
            imgId.push($(this).attr('data-id'));
        })
        var imglist = imgId.join(',');

        if (!desc && imagelen == '0') {
            toast.fail({
                title:"请输入发表内容或图片!",
                duration:1500
            });
            return false;
        } else {

                //发布
            $.ajax({
                url: dns + 'square/publish',
                type: 'POST',
                data: {
                    'img': imglist,
                    'content': desc
                },
                beforeSend: function(request) {
                    request.setRequestHeader("token", localStorage.getItem('token'));
                },
                success: function(res) {
                    // console.log(JSON.stringify(res));
                    if (res.code == '20000') {
                      $("#postAction").attr("disabled","disabled")
                      toast.success({
                          title:res.msg,
                          duration:1500
                      });
                        api.sendEvent({
                          name:"compile_reload"
                        })
                        setTimeout(function() {
                            api.closeWin()
                        }, 1500);

                    }
                },
                error: function(err) {
                    toast.fail({
                        title:JSON.parse(err.responseText).msg,
                        duration:1500
                    });
                    return;
                }
            });
        }
    });
</script>

</html>
